import Model from '../utils/model'
import request from '../utils/request'
import {
  mapGetters
} from 'vuex'
import {
  getUserInfo
} from '../utils/auth'
export default {
  data () {
    return {
      submiting: false,
      listLoading: false,
      list: null,
      params: {},

      isEditing: false,
      dialogFormVisible: false,
      UPLOAD_URL: '/util/upload'
    }
  },
  props: {
    filters: {
      type: Object,
      default: () => {
        return {}
      }
    }
    // ,

    // total:{
    //   type:Number,
    //   default:0
    // }
  },
  created () {
    this._temp = Object.assign({}, this.temp)
  },
  computed: {
    ...mapGetters(['permlist']),
    ...mapGetters(['accessable'])
  },
  methods: {
    apiUrl (url) {
      return process.env.hostAddress + url
    },
    getNow () {
      let date = new Date()
      const w = d => {
        return d > 9 ? d : '0' + d
      }
      return date.getFullYear() + '-' + w(date.getMonth() + 1) + '-' + w(date.getDate()) + ' ' + w(date.getHours()) + ':' + w(date.getMinutes()) +
        ':' + w(date.getSeconds())
    },
    // ~accessable.indexOftoken){
    //   if(this.permlist && this.permlist.length){
    //     return this.permlist.indexOf(token)!=-1;
    //   }
    //   return false;
    // },
    isAdmin () {
      let userInfo = getUserInfo()
      return userInfo.userType == 0
    },
    isProvider () {
      let userInfo = getUserInfo()
      return userInfo.userType == 1
    },
    imgUrl (url) {
      if (!url) {
        return url
      }
      if (url.indexOf('://') != -1) {
        return url
      }
      if (url.indexOf('data:') !== -1) {
        return url
      }
      if (url[0] != '/') {
        url = '/' + url
      }
      if (url.indexOf('/images/') != -1 || url.indexOf('/imgs/') != -1) {
        return url
      }
      if (url.indexOf('/oss-image/') != -1) {
        return 'http://weixin-ostorage01.oss-cn-shenzhen.aliyuncs.com' + url
      }
      return 'https://weixina01.bppc.com.cn/zy-admin/UploadFiles/zy/product' + url
    },
    goodsStatusData () {
      return ['出售中', '下架区']
    },
    authStatus () {
      return ['待审核', '审核中', '审核通过', '审核不通过']
    },
    handleAvatarSuccess (imgField) {
      return (res, file) => {
        if (res && res.errcode == 0) {
          this.temp[imgField] = res.info
        }
      }
    },

    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleUpdate (row) {
      this.__onHandleUpdate && this.__onHandleUpdate(row)
      if (row) {
        Object.keys(this.temp).forEach(key => {
          if (key in row) {
            this.temp[key] = row[key]
          } else {
            if (Array.isArray(this.temp[key]) && this.temp[key].length == 0) {
              this.temp[key] = []
            } else {
              this.temp[key] = ''
            }
          }
        })
        this.__onAfterHandleEditUpdate && this.__onAfterHandleEditUpdate(row)
        this.isEditing = true
      } else {
        Object.keys(this._temp).forEach(key => {
          this.temp[key] = this._temp[key]
        })
        this.isEditing = false
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    init (modelname, mode) {
      this.$model = Model.create(modelname, mode)
      return this
    },
    sortChange (e) {
      //  console.log(e);
      let sort = e.prop
      let order = e.order
      let orderType
      if (order == 'ascending') {
        orderType = 'asc'
      } else if (order == 'descending') {
        orderType = 'desc'
      }
      if (sort && orderType) {
        this.params.order = sort
        this.params.sort = orderType
        this.loadData()
      } else {
        this.params.order = ''
        this.params.sort = ''
        this.loadData()
      }
    },
    _parseFilters () {
      for (let key in this.filters) {
        let value = this.filters[key]
        if (typeof value === 'string') {
          value = value.trim()
        }
        let kv = key.split('$')
        let op = 'eq'
        if (kv.length == 2) {
          key = kv[1]
          op = kv[0]
        }
        if (value && this.__onParseFilterValue) {
          value = this.__onParseFilterValue(key, op, value)
        }
        this.$model.where({
          [key]: [op, value]
        })
      }
      return this
    },
    getFilterRules () {
      return this.$model.filterBuilder.toString()
    },
    _parseParams () {
      this.$model.addParam(this.params)
      return this
    },
    combOptions (modelname, filters) {
      return request({
        url: '/admin/query/options',
        method: 'get',
        params: {
          model: modelname,
          filterRules: JSON.stringify(filters) || ''
        }
      })
    },
    setFilterAsPostParam () {
      this.$model.filterAsPostParam = 1
    },
    getToday () {
      let date = new Date()

      function w (t) {
        return t > 9 ? t : '0' + t
      }
      return date.getFullYear() + '-' + w(date.getMonth() + 1) + '-' + w(date.getDate())
    },
    loadData () {
      this._parseFilters()
      this._parseParams()
      this.listLoading = true
      this.$model
        .select()
        .then(info => {
          this.listLoading = false
          this.list = info.rows
          this.total = info.total
        })
        .catch(res => {
          this.listLoading = false
        })
    },
    handleSizeChange (size) {
      this.$model.addParam('limit', size)
      this.loadData()
    },
    addParam (key, value) {
      this.$model.addParam(key, value)
      return this
    },
    $success (msg) {
      this.$message({
        type: 'success',
        message: msg || '操作成功!'
      })
    },
    $warning (msg) {
      this.$message({
        type: 'warning',
        message: msg
      })
    },
    $$notify (msg) {
      this.$notify({
        title: '成功',
        message: msg || '操作成功',
        type: 'success',
        duration: 2000
      })
    },
    $error (msg) {
      this.$message({
        type: 'error',
        message: msg
      })
    },
    $$comfirm (msg, sureCallback) {
      this.$confirm(msg, '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(sureCallback).catch(_ => {})
    },
    handleFilter () {
      this.$model.addParam('page', 1)
      this.loadData()
    },
    $query (method, data) {
      return this.$get(method, data)
    },
    $get (url, params) {
      return request({
        url,
        method: 'get',
        params
      })
    },
    submitFormAction () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.__onFormSubmit) {
            if (this.__onFormSubmit() === false) {
              this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
              })
              return
            }
          }
          this.submiting = true
          let func = null
          if (this.isEditing) {
            func = this.$model.save
          } else {
            func = this.$model.add
          }

          func
            .call(this.$model, this.temp)
            .then(() => {
              this.submiting = false
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              if (this.__onFormSubmited && this.__onFormSubmited() === false) {
                return
              }
              this.loadData()
            })
            .catch((info) => {
              this.submiting = false
              // this.$message({
              //   type: "warning",
              //   message: info || "更新失败!"
              // });
            })
        }
      })
    },
    handleDelete (row) {
      this.$confirm('确认要删除吗？', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$model
          .removeById(row.id)
          .then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            if (this.__onRowRemoved && this.__onRowRemoved(row) === false) {
              return
            }
            this.loadData()
          })
          .catch((info) => {
            // this.$message({
            //   type: "warning",
            //   message: info || "删除失败"
            // });
          })
      })
    },
    handleCurrentChange (val) {
      this.$model.addParam('page', val)
      this.loadData()
    },
    $post (url, data) {
      return request({
        url,
        method: 'POST',
        data
      })
    },
    $postJson (url, data) {
      return request.post(url, data, {
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      })
    },
    exportExcel (options) {
      this._parseFilters()
      this._parseParams()
      return this.$model.addParam(options).query('/admin/' + this.$model.modelname + '/exportExcel')
    },
    exportExcel1 (options) {
      this._parseFilters()
      this._parseParams()
      return this.$model.addParam(options).query('/admin/' + this.$model.modelname + '/export')
    },
    parseArr2Params (keyname, arr) {
      let rt = {}
      for (let i = 0; i < arr.length; i++) {
        let keyPrefix = keyname + '[' + i + ']'
        let row = arr[i]
        if (typeof row === 'object') {
          Object.keys(row).forEach(key => {
            rt[keyPrefix + '.' + key] = row[key]
          })
        } else {
          rt[keyPrefix] = row
        }
      }
      return rt
    },
    openWin (newUrl) {
      let iframe = document.createElement('iframe')
      iframe.style.display = 'none'
      let form = document.createElement('form')
      form.action = newUrl
      form.method = 'get'
      form.target = '_self'
      iframe.appendChild(form)
      document.body.appendChild(iframe)
      form.submit()
      setTimeout(() => {
        iframe.parentElement.removeChild(iframe)
      }, 100)
    },
    exportExcelWithForm (newUrl, queryParams) {
      let iframe = document.createElement('iframe')
      iframe.style.display = 'none'
      let form = document.createElement('form')
      form.action = newUrl
      form.method = 'post'
      form.target = '_self'
      if (queryParams) {
        Object.keys(queryParams).forEach(field => {
          const inputField = document.createElement('input')
          inputField.name = field
          inputField.type = 'hidden'
          inputField.value = queryParams[field]
          form.appendChild(inputField)
        })
      }
      iframe.appendChild(form)
      document.body.appendChild(iframe)
      form.submit()
      setTimeout(() => {
        iframe.parentElement.removeChild(iframe)
      }, 100)
    }
  }
}
